﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace VideoSystem
{
    public class DBConnection
    {
        public static readonly string connectionString = @"Data Source=balder.ucn.dk;database=dm75_4;
                                                            User id=DM75_4;Password=MaaGodt";

        public static readonly SqlConnection dbConn = new SqlConnection(connectionString);

        private static SqlCommand dbCmd;

        public static void Open()
        {
            try
            {
                if (dbConn.State != System.Data.ConnectionState.Open)
                    dbConn.Open();
                Console.WriteLine("Connection open");
            }
            catch(Exception e)
            {
                Console.WriteLine("Failed opening connection");
                Console.WriteLine(e.Message);
            }

        }

        public static void CloseConnection()
        {
            try
            {
                dbConn.Close();
                Console.WriteLine("The connection is closed");
            }
            catch (Exception e)
            {
                Console.WriteLine("Error closing connection");
                Console.WriteLine(e.Message);
            }
        }

        public static SqlCommand GetDbCommand(string sql)
        {
            if (dbConn.State != System.Data.ConnectionState.Open)
            {
                dbConn.Open();
            }
            if (dbCmd == null)
            {
                dbCmd = new SqlCommand(sql, dbConn);
            }
            dbCmd.Parameters.Clear();
            dbCmd.CommandText = sql;
            return dbCmd;
        }
    }
}
